package com.example.cardgame

import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.cardgame.databinding.ActivityMainBinding
import java.io.Serializable

const val KEY_PROFILE = "profile"
const val KEY_SCORE = "SCORE"
data class Person(val name: String, val gender: String, val sid: String, val phone: String, val email: String, val hobby: String, val score: Int): Serializable
class MainActivity : AppCompatActivity() {
    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    var highestScore: Int = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(binding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        binding.buttonGame.setOnClickListener {
            val intent = Intent(this, CardGameActivity::class.java)
            startActivity(intent)
        }

        val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val data: Intent ?= result.data
                val person: Person ?= if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    data?.getSerializableExtra(KEY_PROFILE, Person::class.java)
                } else {
                    data?.getSerializableExtra(KEY_PROFILE) as Person
                }
                person?.let{
                    binding.nameText.text = it.name
                    binding.genderText.text = it.gender
                    binding.sidText.text = it.sid
                    binding.phoneText.text = it.phone
                    binding.emailText.text = it.email
                    binding.hobbyText.text = it.hobby
                    binding.scoreText.text = highestScore.toString()
                }
            }
        }

        binding.buttonEdit.setOnClickListener {
            val intent = Intent(this, EditActivity::class.java)
            launcher.launch(intent)
        }

        val score = intent.getIntExtra(KEY_SCORE, 0)
        if (score > highestScore) {
            highestScore = score
        }

        binding.scoreText.text = highestScore.toString()
    }
}